import {
  getShopBookingInfo,
  submitSpaBookingUpgrade
} from '@/api/spa'
import {
  getShopIndex
} from '@/api/shop'
import {
  showSuccess,
  showText
} from "@/utils/util";
import {
  checkShopAuth
} from "@/api/shop";
import {
  apiUrl
} from '@/api/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUri: getApp().globalData.imgUri,
    cdn: getApp().globalData.cdn,
    showManage: false, // 门店管理信息
    showUpgrade: false, // 确认升单信息
    showUpgradeResult: false, // 升单成功
    showUpgradeConfirm: false, // 确认继续提交
    showWrite: false,
    writeOkShow: false,
    bookingId: 0,
    shopInfo: {},

    receiptImg:'', // 交易单据图片地址
  },
  closeDialog(e) {
    let {
      type
    } = e.currentTarget.dataset
    this.setData({
      [type]: false
    })
  },
  // 上传单据
  uploadReceipt(){
    wx.chooseMedia({
      count:1,
      mediaType:['image'],
      sourceType: ['album', 'camera'],
      success:(res) =>{
        console.log(res.tempFiles)
        res.tempFiles.map(r=>{
          this.upload(r.tempFilePath)
        })
      }
    })
  },
  upload(detail){
    let url = apiUrl + '/file/uploadFile'
    // 上传图片
    wx.uploadFile({
      filePath: detail,
      name: 'file',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('access_token')
      },
      url: url,
      success: (res) => {
        let res1 = JSON.parse(res.data)
        console.log(res1.data.url)
        this.setData({
          receiptImg: res1.data.url
        })
      },
      fail: (err) => {
        console.log('Url:', url, ' err:', err)
      }
    })
  },
  // 确认提交交易单据
  bindUpgradeConfirm() {
    if(!this.data.receiptImg){
      showText('请上传交易单据')
      return
    }
    submitSpaBookingUpgrade({
      bookingId:this.data.bookingId,
      upgrade:true,
      upgradeCredential:this.data.receiptImg
    }).then(res=>{
      if(res.code == 200){
        showSuccess('操作成功')
        this.setData({
          showUpgradeConfirm: false
        })
      }else{
        showText(res.msg)
      }
    })
  },
  // 继续提交交易单据
  bindUpgradeResult() {
    this.setData({
      showUpgradeResult: false,
      showUpgradeConfirm: true
    })
  },
  // 确认升单接口
  confirmUpgrade() {
    submitSpaBookingUpgrade({
      bookingId:this.data.bookingId,
      upgrade:true
    }).then(res=>{
      if(res.code == 200){
        this.setData({
          showUpgrade: false,
          showUpgradeResult: true
        })
      }else{
        showText(res.msg)
      }
    })
    
  },
  // 扫码核销
  openScan_hexiao() {
    let _this = this;
    wx.scanCode({
      success(res) {
        if (res.result) {
          var result = res.result;
          var arr_result = result.split("=");
          console.log(result,'扫描结果')
          if (arr_result[0]) {
            if (arr_result[0] == "bookingId") {
              var bookingId = arr_result[1];
              _this.setData({
                bookingId: bookingId
              })
              let shopToken = wx.getStorageSync('shopToken');
              getShopBookingInfo({
                bookingId: bookingId,
                shopToken: shopToken
              }).then(res => {
                if (res.code == 200) {
                  if (res.data.status == 2) {
                    wx.showModal({
                      title: '提示',
                      content: '已核销，无需再次核销',
                      showCancel: false,
                    });
                  } else {
                    _this.openshowWrite_hexiao(res.data);
                  }
                }else{
                  wx.showModal({
                    title: '提示',
                    content: res.msg,
                    showCancel: false,
                  });
                }
              });
            } else {
              wx.showModal({
                title: '提示',
                content: '扫码失败',
                showCancel: false,
              });
            }
          } else {
            wx.showModal({
              title: '提示',
              content: '扫码失败',
              showCancel: false,
            });
          }


        }

      }
    })

  },
  // 升单
  openScan_shengdan() {
    let _this = this;
    wx.scanCode({
      success(res) {
        if (res.result) {
          var result = res.result;
          var arr_result = result.split("=");
          console.log(result,'扫描结果')
          if (arr_result[0]) {
            if (arr_result[0] == "bookingId") {
              var bookingId = arr_result[1];
              _this.setData({
                bookingId: bookingId
              })
              let shopToken = wx.getStorageSync('shopToken');
              getShopBookingInfo({
                bookingId: bookingId,
                shopToken: shopToken
              }).then(res => {
                if (res.code == 200) {
                  if (res.data.status != 2) {
                    wx.showModal({
                      title: '提示',
                      content: '请先核销',
                      showCancel: false,
                    });
                  } else {
                    _this.openshowWrite_shengdan(res.data);
                  }
                }else{
                  wx.showModal({
                    title: '提示',
                    content: res.msg,
                    showCancel: false,
                  });
                }
              });
            } else {
              wx.showModal({
                title: '提示',
                content: '扫码失败',
                showCancel: false,
              });
            }
          } else {
            wx.showModal({
              title: '提示',
              content: '扫码失败',
              showCancel: false,
            });
          }


        }

      }
    })

  },
  openshowWrite_hexiao(data) {
    let params = {
      name: data.name,
      spaName: data.spaName,
      bookingId: this.data.bookingId,
      gender: data.gender,
      mobile: data.mobile,
      shop: data.shop,
    };
    console.log(params);
    this.setData({
      params
    });

    if(data.status == 1){
      this.setData({
        showWrite: true
      });
    }


  },
  openshowWrite_shengdan(data) {
    let params = {
      name: data.name,
      spaName: data.spaName,
      bookingId: this.data.bookingId,
      gender: data.gender,
      mobile: data.mobile,
      shop: data.shop,
    };
    console.log(params);
    this.setData({
      params
    });

    // 如果status == 2（核销成功） && scoreTime（已评分） && !upgradeTime (未升单)，弹出确认升单
    if(data.status == 2 && !data.upgradeTime){
      if(!data.scoreTime){
        wx.showModal({
          title: '提示',
          content: '请先评分',
          showCancel: false,
        });
      }else{
        this.setData({
          showUpgrade: true,
        });
      }
    }

    if(data.status == 2 && data.upgradeTime){
      wx.showModal({
        title: '提示',
        content: '已升单成功',
        showCancel: false,
      });
    }
  },

  closeWrite() {
    this.setData({
      showWrite: false
    })
  },
  writeOk() {
    let shopToken = wx.getStorageSync('shopToken');
    getShopIndex({
      shopToken
    }).then(res => {
      if (res.code == 200) {
        this.setData({
          shopInfo: res.data,
          showWrite: false,
          writeOkShow: true
        })
      } else {

      }
    })

  },
  closeWriteOkShow() {

    this.setData({
      showWrite: false,
      writeOkShow: false
    })
  },
  writeContinu() {
    this.setData({
      showWrite: false,
      writeOkShow: false
    })
    this.openScan_hexiao()
  },

  bindconfirm() {
    wx.navigateTo({
      url: '/shop/manage/manage',
    })
  },
  bindconfirm2() {
    wx.navigateTo({
      url: '/shop/records/records',
    })
  },

  drawCircle(step, id) {
    const query = wx.createSelectorQuery()
    query.select(`#${id}`)
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        const context = canvas.getContext('2d');
        canvas.height = canvas.width;
        let x = canvas.width / 2;
        let y = canvas.height / 2;
        context.beginPath();
        // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
        context.arc(x, y, x - 10, -Math.PI / 2, 2 * Math.PI - Math.PI / 2, false);
        context.fillStyle = 'transparent'; // 圆环内部为空
        context.strokeStyle = 'rgba(255, 255, 255, 0.51)';
        context.lineWidth = 5;
        context.stroke();

        context.beginPath();
        let grd = context.createLinearGradient(0, 0, 170, 0);
        grd.addColorStop("0", "rgb(253, 240, 219) ");
        grd.addColorStop("1", "rgb(208, 184, 146)");
        context.arc(x, y, x - 10, -Math.PI / 2, step * Math.PI - Math.PI / 2, false);
        context.fillStyle = 'transparent'; // 圆环内部为空
        context.strokeStyle = grd;
        context.lineWidth = 10;
        context.stroke();
        // context.draw()
      })
  },
  //num  百分比
  // type 1 累计  2 今日
  drawOne(num, type) {
    let sep = num / 100 * 2;
    if (type == 1) {
      this.drawCircle(sep, 'canvasProgress')
    } else {
      this.drawCircle(sep, 'canvasProgress2')
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let shopToken = wx.getStorageSync('shopToken');
    console.log(shopToken);
    if (!shopToken) {
      wx.redirectTo({
        url: '/shop/login/login',
      })
    } else {
      checkShopAuth({
        shopToken: shopToken
      }).then(res => {
        if (res.code == 200) {

        } else {
          wx.removeStorageSync('shopToken');
          wx.navigateTo({
            url: '/shop/login/login',
          });
        }
      })

      getShopIndex({
        shopToken
      }).then(res => {
        if (res.code == 200) {
          this.setData({
            shopInfo: res.data
          })
        } else {

        }
      })
    }
  },
  topage() {
    // showText('您好，该活动暂未开始，敬请期待！')
    this.setData({
      showManage: true
    })
  },
  topage2() {
    wx.navigateTo({
      url: '/shop/reservation/reservation',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // this.drawOne(30, 1);
    // this.drawOne(80, 2);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})